/**********************************************************************************
Copyright [2012] [APS-PK]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***********************************************************************************/
package aps.example.facedetector;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class FaceDetectorView extends SurfaceView implements SurfaceHolder.Callback {

	private Camera mCamera = null;
	private SurfaceHolder mHolder = null;
	
	public FaceDetectorView(Context context, Object obj) {
		super(context);
		
		try {
			mCamera = (Camera)obj;
			mHolder = getHolder();
			mHolder.addCallback(this);
		} catch (Exception e) {
			Log.d("[ERROR]", e.getMessage());
		}
	}
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {				
		if(mHolder != null){
			synchronized (mHolder) {
				this.StopCamera();
				this.StartCamera();	
			}
		}
	}

	public void surfaceCreated(SurfaceHolder holder) {
		if(mHolder != null){
			synchronized (mHolder) {
				this.StartCamera();
			}
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		if(mHolder != null){
			synchronized (mHolder) {
				this.StopCamera();
				this.ReleaseCamera();
			}
		}
	}
	
	private void StartCamera(){
		
		try {
			if(mCamera != null){
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();
			}
		} catch (Exception e) {
				Log.d("[ERROR]", e.getMessage());
		}
	}
	private void StopCamera(){
		
		try {
			if(mCamera != null)
				mCamera.stopPreview();
		} catch (Exception e) {
				Log.d("[ERROR]", e.getMessage());
		}		
	}
	private void ReleaseCamera()
	{
		try {
			if(mCamera != null)
				mCamera.release();
		} catch (Exception e) {
			Log.d("[ERROR]", e.getMessage());
		}
	}
}
